package com.meals.system.api.user;

import com.meals.system.api.user.param.SaveCartItemParam;
import com.meals.system.api.user.param.UpdateCartItemParam;
import com.meals.system.api.user.vo.WhitesMealShoppingCartItemVO;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.config.annotation.TokenToSystemUser;
import com.meals.system.entity.SystemUser;
import com.meals.system.entity.WhitesMealShoppingCartItem;
import com.meals.system.service.WhitesMealShoppingCartService;
import com.meals.system.util.PageQueryUtil;
import com.meals.system.util.PageResult;
import com.meals.system.util.Result;
import com.meals.system.util.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/10
 */
@RestController
@Api(value = "v1", tags = "3-4.白餐系统用户购物车相关接口")
@RequestMapping("/user-api/v1")
public class WhitesMealUserShoppingCartAPI {

    @Resource
    private WhitesMealShoppingCartService whitesMealShoppingCartService;

    @GetMapping("/shop-cart/page")
    @ApiOperation(value = "购物车列表(每页默认5条)", notes = "传参为页码")
    public Result<PageResult<List<WhitesMealShoppingCartItemVO>>> cartItemPageList(Integer pageNumber, @TokenToSystemUser SystemUser loginSystemUser) {
        Map params = new HashMap(8);
        if (pageNumber == null || pageNumber < 1) {
            pageNumber = 1;
        }
        params.put("userId", loginSystemUser.getUserId());
        params.put("page", pageNumber);
        params.put("limit", Constants.SHOPPING_CART_PAGE_LIMIT);
        //封装分页请求参数
        PageQueryUtil pageUtil = new PageQueryUtil(params);
        return ResultGenerator.genSuccessResult(whitesMealShoppingCartService.getShoppingCartItems(pageUtil));
    }

    @GetMapping("/shop-cart")
    @ApiOperation(value = "购物车列表(网页移动端不分页)", notes = "")
    public Result<List<WhitesMealShoppingCartItemVO>> cartItemList(@TokenToSystemUser SystemUser loginSystemUser){
        return ResultGenerator.genSuccessResult(whitesMealShoppingCartService.getShoppingCartItems(loginSystemUser.getUserId()));
    }

    @PostMapping("/shop-cart")
    @ApiOperation(value = "添加商品到购物车接口", notes = "传参为商品id、数量")
    public Result saveWhitesMealShoppingCartItem(@RequestBody SaveCartItemParam saveCartItemParam,
                                                 @TokenToSystemUser SystemUser loginSystemUser){
        String saveResult = whitesMealShoppingCartService.saveWhitesMealCartItem(saveCartItemParam, loginSystemUser.getUserId());
        // 添加成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(saveResult)){
            return ResultGenerator.genSuccessResult();
        }
        // 添加失败
        return ResultGenerator.genFailResult(saveResult);
    }

    @PutMapping("/shop-cart")
    @ApiOperation(value = "修改购物项数据", notes = "传参为购物项id、数量")
    public Result updateWhitesMealShoppingCartItem(@RequestBody UpdateCartItemParam updateCartItemParam,
                                                   @TokenToSystemUser SystemUser loginSystemUser){
        String updateResult = whitesMealShoppingCartService.updateWhitesMealCartItem(updateCartItemParam,loginSystemUser.getUserId());
        // 修改成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(updateResult)){
            return ResultGenerator.genSuccessResult();
        }
        // 修改失败
        return ResultGenerator.genFailResult(updateResult);
    }

    // 对于登录账号是否有权限操作数据（登录数据的userId是否对应操作数据的userId）
    // 可以在两个地方进行检查，
    // 第一个是在API文档中，例子 updateWhitesMealShoppingCartItem
    // 第二个是在Service中 例子 deleteWhitesMealShoppingCartItem
    @DeleteMapping("/shop-cart/{cartItemId}")
    @ApiOperation(value = "删除购物项", notes = "传参为购物项id")
    public Result deleteWhitesMealShoppingCartItem(@PathVariable("cartItemId") Long cartItemId,
                                                   @TokenToSystemUser SystemUser loginSystemUser){
        WhitesMealShoppingCartItem whitesMealShoppingCartItem = whitesMealShoppingCartService.getWhitesMealCartItemById(cartItemId);
        if (!loginSystemUser.getUserId().equals(whitesMealShoppingCartItem.getUserId())){
            return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }
        Boolean deleteResult = whitesMealShoppingCartService.deleteById(cartItemId,loginSystemUser.getUserId());
        // 删除成功
        if (deleteResult){
            return ResultGenerator.genSuccessResult();
        }
        // 删除失败
        return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
    }

    @GetMapping("/shop-cart/settle")
    @ApiOperation(value = "根据购物项id数组查询购物项明细", notes = "确认订单页面使用")
    public Result<List<WhitesMealShoppingCartItemVO>> toSettle(Long[] cartItemIds, @TokenToSystemUser SystemUser loginSystemUser){
        if (cartItemIds.length < 1){
            SystemException.fail("参数异常");
        }
        int priceTotal = 0;
        List<WhitesMealShoppingCartItemVO> itemsForSettle = whitesMealShoppingCartService.getCartItemsForSettle(Arrays.asList(cartItemIds), loginSystemUser.getUserId());
        if (CollectionUtils.isEmpty(itemsForSettle)){
            // 无数据则抛出异常
            SystemException.fail("参数异常");
        } else {
            // 总价
            for (WhitesMealShoppingCartItemVO whitesMealShoppingCartItemVO : itemsForSettle){
                priceTotal += whitesMealShoppingCartItemVO.getGoodsCount() * whitesMealShoppingCartItemVO.getSellingPrice();
            }
            if (priceTotal < 1){
                SystemException.fail("价格异常");
            }
        }
        return ResultGenerator.genSuccessResult(itemsForSettle);
    }
}
